import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, FormControl, Validators, AbstractControl } from '@angular/forms';
import { NzMessageService } from 'ng-zorro-antd';

// services
import { ConstantService } from '../../../../../core/services/constant.service';
import { ServerService } from '../../../../../core/services/server.service';
import { StorageService } from '../../../../../core/services/storage.service';

@Component({
    selector: 'app-role-management',
    templateUrl: './role-management.component.html',
    styleUrls: ['./role-management.component.css']
})

export class RoleManagementComponent implements OnInit {
    roleForm: FormGroup;                // 角色表单
    isVisible: boolean = false;         // 是否显示modal
    isConfirmLoading: boolean = false;  // modal中点击保存的时候的过渡效果
    isViewStateUpdate: boolean = false; // 页面是否是更新状态
    roleList: object[] = [];            // 全部角色列表
    schoolId: string;                   // 学校id
    menuList: object[] = [];            // 菜单列表
    _current: number = 1;               // 当前页
    _pageSize: number = 10;             // 每页数量
    _total: number = 1;                 // 数据总数
    _loading: boolean = true;           // 加载动画

    constructor(
        private fb: FormBuilder,
        private constant: ConstantService,
        private server: ServerService,
        private storage: StorageService,
        private message: NzMessageService
    ) {
        /**
         * 初始化班级表单
         * name: 班级名称
         * menuIds: 菜单id
         */
        this.roleForm = this.fb.group({
            _id: [null],
            name: [null, [Validators.required, Validators.maxLength(10)]],
            menuIds: [null, Validators.required]
        });
        this.schoolId = this.storage.getItem(this.constant.storage.currentUser)['schoolId']['_id'];
    }

    ngOnInit() {
        this.getAllRoles();
    }

    /**
     * 显示modal,添加或更新班级信息
     * @param id 
     */
    async showModal(id) {
        this.isVisible = true;
        // 首先获取年级列表和学科列表
        await this.getAllMenus();
        if (id) {
            this.isViewStateUpdate = true;
            const result = await this.server.fetch(this.constant.api.manage.role.findOne, { id });
            if (result) {
                this.roleForm.controls._id.setValue(result.data._id);
                this.roleForm.controls.name.setValue(result.data.name);
                this.roleForm.controls['menuIds'].setValue(result.data.menuIds);
            }
        } else {
            this.roleForm.reset();
            this.isViewStateUpdate = false;
        }
    }

    /**
     * 获取年级列表
     * @param schoolId 
     */
    async getAllMenus() {
        const allMenus = await this.server.fetch(this.constant.api.manage.role.menus, {});
        if (allMenus) {
            this.menuList = allMenus.data;
        }
    }

    /**
     * 关闭modal
     * @param e 
     */
    handleCancel(e): void {
        this.isVisible = false;
    }

    // 获取表单项
    getFormControl(name): AbstractControl {
        return this.roleForm.controls[name];
    }

    /**
     * 保存 || 更新
     * @param e 
     * @param school 
     */
    async handleOk(e, role): Promise<void> {
        role.schoolId = this.schoolId;
        this.isConfirmLoading = true;
        // 保存
        const result = await this.server.fetch(this.constant.api.manage.role[this.isViewStateUpdate ? 'update' : 'save'], role);
        if (result) {
            this.message.success('保存角色成功');
            if (!this.isViewStateUpdate) {
                // 清空表单
                this.roleForm.controls['name'].reset();
            }
            this.isConfirmLoading = false;
            this.getAllRoles();
            this.isVisible = false;
        } else {
            this.isConfirmLoading = false;
        }

    }

    /**
     * 获取全部班级列表
     */
    async getAllRoles(): Promise<void> {
        const param = {
            schoolId: this.schoolId,
            limit: this._pageSize
        };
        if (this._current !== 1) {
            param['date'] = this.roleList[this.roleList.length - 1]['createDate'];
        }
        const allRoles = await this.server.fetch(this.constant.api.manage.role.findAll, param);
        if (allRoles) {
            this.roleList = allRoles.data.data;
            this._total = allRoles.data.count;
            this._loading = false;
            // 转换角色数据
            if (this.roleList.length > 0) {
                for (let m of this.roleList) {
                    if (m['menuIds'].length > 0) {
                        let str = [];
                        for (let menu of m['menuIds']) {
                            str.push(menu.name);
                        }
                        m['menuIds'] = str.join(' | ');
                    } else {
                        m['menuIds'] = '暂无';
                    }
                }
            }
        } else {
            this._loading = false;
        }
    }
}
